package removeAnagrams;

import java.util.*;

public class Solution {
    public List<String> removeAnagrams(String[] words) {
        List<String> ans = new ArrayList<>();
        for (String word: words) {
            ans.add(word);
        }
        for (int i = 1; i < ans.size(); i++) {
            if(check(ans.get(i),ans.get(i-1))) {
                ans.remove(i);
                i--;
            }
        }
        return ans;
    }
    private boolean check(String a,String b) {
        if(a.length()!=b.length()) {
            return false;
        }
        Map<Character,Integer> map1 = new HashMap<>();
        Map<Character,Integer> map2 = new HashMap<>();
        for (char c: a.toCharArray()) {
            map1.put(c,map1.getOrDefault(c,0)+1);
        }
        for (char c: b.toCharArray()){
            map2.put(c,map2.getOrDefault(c,0)+1);
        }
        for (Character key: map1.keySet()) {
            if(map1.get(key)!=map2.getOrDefault(key,0)) return false;
        }
        return true;
    }
}
